var StudentsFee = {

    selected_row_id:null,
    objGrid:null,
    paginate:{},
    export_limit:10000,

    init:function () {
        var self = this;

        self.objGrid = $('#flex').flexigrid({
            url:$('#table-url').val(),
            dataType:'json',
            colModel:[
                {display:'ID', name:'id', width:20, sortable:false, align:'left', hide:true},
                {display:'Index Number', name:'index_number', width:80, sortable:false, align:'center', hide:false},
                {display:'Name', name:'name', width:200, sortable:false, align:'center', hide:false},
                {display:'Level', name:'level', width:60, sortable:false, align:'center', hide:false},
                {display:'Program', name:'program_id', width:150, sortable:false, align:'center', hide:false},
                {display:'Total Bill', name:'fee_amount', width:100, sortable:false, align:'center', hide:false},
                {display:'Total Paid', name:'paid', width:100, sortable:false, align:'center', hide:false},
                {display:'Total Owned', name:'owed', width:100, sortable:false, align:'center', hide:false}
            ],
            formFields:[
               /* {type:'buttom', name:'New', bclass:'add', onpress:self.handleGridEvent},
                {separator:true},
                {type:'buttom', name:'Save', bclass:'save', onpress:self.handleGridEvent},
                {separator:true},
                {type:'buttom', name:'Edit', bclass:'edit', onpress:self.handleGridEvent},
                {separator:true},
                {type:'buttom', name:'Cancel', bclass:'cancel', onpress:self.handleGridEvent},
                {separator:true},
                {type:'buttom', name:'Delete', bclass:'delete', onpress:self.handleGridEvent},
                {separator:true},
                {type:'buttom', name:'Reset Password', bclass:'enable', onpress:self.handleGridEvent}*/
                {type:'select',name: 'Filter Program', id: 'filter_program',bclass: 'filter',width:'100',onchange:self.handleGridEvent,options:program_types},
                {separator:true},
                {type:'select',name: 'Filter Level', id: 'filter_level',bclass: 'filter',onchange:self.handleGridEvent,options:levels},
                {separator:true},
                {type:'select',name: 'Filter Year', id: 'filter_academic_session',bclass: 'filter',onchange:self.handleGridEvent,options:academic_sessions,defval:current_aca_ses},
                {separator:true},
                {type:'buttom', name:'Export', bclass:'export', onpress:self.handleGridEvent},
                {separator:true}
            ],
            searchitems:[
                {display:'Index Number', name:'index_number', isdefault:true},
                {display:'Name', name:'name'},
                {display:'Level', name:'level'}
             ],
            checkboxSelection:false,
            editablegrid:{
                use:false
            },
            columnControl:false,
            sortname:"id",
            sortorder:"desc",
            usepager:true,
            useRp:true,
            rp:15,
            showTableToggleBtn:false,
            height:300,
            subgrid:{
                use:true,
                url:$('#table-details-url').val(),
                params:[
                    {name: 'academic_session', value:''}
                ],
                colModel:[
                    {display:'Fee', name:'fee_type_id', width:250, align:'center', editable:{form:'select', validate:'', defval:'', options:fee_types}},
                    {display:'Amount', name:'amount', width:100, align:'center', editable:{form:'text', validate:'empty,decimalNumber', defval:''}},
                    {display:'Paid', name:'paid', width:100, align:'center'},
                    {display:'Owed', name:'owed', width:100, align:'center'}
                ],
                editablegrid:{
                    use:true,
                    url:$('#table-editable-sub-url').val()
                    /*callback:function (server_response) {
                        if (server_response.code == 0) {
                            jLib.message('Data Status', server_response.msg, 'success');
                        }
                        else {
                            jLib.message('Data Status', server_response.msg, 'error');
                        }
                    }*/
                },
                formFields:[
                    {type:'buttom', name:'New', bclass:'new', onpress:self.handleSubGridEvent},
                    {separator:true},
                    {type:'buttom', name:'Edit', bclass:'edit', onpress:self.handleSubGridEvent},
                    {separator:true},
                    {type:'buttom', name:'Save', bclass:'save', onpress:self.handleSubGridEvent},
                    {separator:true},
                    {type:'buttom', name:'Cancel', bclass:'print', onpress:self.handleSubGridEvent},
                    {separator:true},
                    {type:'buttom', name:'Delete', bclass:'delete', onpress:self.handleSubGridEvent}
                ]
            }
        });

        self.objGrid[0].p.subgrid.params[0]['value'] = $("#filter_academic_session").val();

        $("#reset_modal form").submit(function(e) {
            e.preventDefault();
            self.doResetPassword();
        });

        $("#import").click(function (e) {
            e.preventDefault();
            var url = $(this).attr('href');
            window.open(url, "Import", "menubar=yes, width=600, height=500,location=no,status=no,scrollbars=yes,resizable=yes");
        });

        self.configureExport();
    },

    handleGridEvent:function (com, inner_table,json) {
        if (com == 'Filter Program' || com == 'Filter Level' || com == 'Filter Year') {
            StudentsFee.filterGrid(json);
        }
        else if(com == 'Export'){
            StudentsFee.processExportBill();
        }
    },

    handleSubGridEvent:function (com, inner_table,json) {
        if (com == 'New') {
            StudentsFee.objGrid.flexBeginSubAdd(inner_table);
        }
        else if (com == 'Edit') {
            var rows = FlexObject.getSelectedSubRows(inner_table);
            //we only need to edit the first one we can't do multiple editing
            if (rows.length > 0) {
                StudentsFee.objGrid.flexBeginSubEdit(rows[0]);
            }
        }
        else if (com == 'Save') {
            StudentsFee.objGrid.flexSubSaveChanges();
        }
        else if (com == 'Cancel') {
            StudentsFee.objGrid.flexSubCancel();
        }
        else if (com == 'Delete') {
            if (FlexObject.rowSubSelectedCheck(inner_table)) {
                StudentsFee.delete_(inner_table);
            }
        }
    },

    filterGrid:function(json){
        var self = this;
        var filter_level = $("#filter_level").val();
        var filter_program = $("#filter_program").val();
        var filter_academic_session = $("#filter_academic_session").val();
        self.objGrid[0].p.subgrid.params[0]['value'] = filter_academic_session;
        $(StudentsFee.objGrid).flexOptions({
            params: [
                {name: 'filter_level', value: filter_level},
                {name: 'filter_program', value: filter_program},
                {name: 'filter_academic_session', value: filter_academic_session}
            ]
        }).flexReload();
    },

    delete_:function (grid) {
        var self = this;
        var url = $('#sub-delete-url').val();
        jLib.do_sub_delete(url, grid);
    },

    processExportBill: function(){
        var self = this;
        $('#export_modal .modal-body .control-group strong').html('Processing Please Wait ...');
        $('#export_modal .modal-footer').hide();
        $('#export_modal').modal({
            backdrop: 'static',
            show: true,
            keyboard: true
        });
        var filter_level = $("#filter_level").val();
        var filter_program = $("#filter_program").val();
        var filter_program_name = $("#filter_program option:selected").text();
        var filter_academic_session = $("#filter_academic_session").val();
        var search_box = $(".qsbox").val();
        var search_column = $(".qscol").val();

        var url = $('#pre-process-export-url').val();
        var query = 'filter_program='+filter_program+'&filter_level='+filter_level+'&query_column='+search_column+'&query='+search_box;

        $.ajax({
            url:url,
            data:query,
            dataType:'json',
            type:'POST',
            success:function (response) {
                var txt = '';
                if (typeof response.msg == 'object') {
                    for (megTxt in response.msg) {
                        txt += response.msg[megTxt] + '<br />';
                    }
                }
                else {
                    txt = response.msg
                }
                if (response.code === 0) {
                    var total = parseInt(response.total);
                    var total_pages = Math.ceil(total / self.export_limit);
                    var pages = [];
                    for(var x=1; x<=total_pages; x++){
                        pages.push(x);
                    }
                    self.paginate['params'] = {
                        filter_level:filter_level,
                        filter_program:filter_program,
                        filter_program_name:filter_program_name,
                        search_box:search_box,
                        search_column:search_column,
                        academic_year:filter_academic_session
                    }
                    self.paginate['pages'] = pages;
                    self.paginate['total_pages'] = total_pages;
                    self.paginate['next_page'] = 1;

                    $('#export_modal .modal-body .control-group #con_program').html((filter_program == 0)?'All':filter_program_name);
                    $('#export_modal .modal-body .control-group #con_level').html((filter_level == 0)?'All':filter_level);
                    $('#export_modal .modal-body .control-group #con_custom_search').html(search_box);
                    $('#export_modal .modal-body .control-group #con_academic_year').html(filter_academic_session);

                    var mesg = "You have a total of "+total_pages+" pages to export. Export will have to be done per page, and the current export must finish before you can start exporting the next page. Please click the 'Begin Export Page 1' button to start exporting. ";
                    if(total_pages == 1){
                         mesg = "You have a total of 1 page to export. Please click the 'Begin Export Page 1' button to start exporting. ";
                    }
                    $('#export_modal .modal-body .control-group strong').html(mesg);
                    $('#export_modal .modal-footer #export_now_btn').removeAttr('disabled');
                    $('#export_modal .modal-footer #export_now_btn').show();
                    $('#export_modal .modal-footer #export_now_btn').html("Begin Export: Page 1");
                    $('#export_modal .modal-footer #export_cancel_btn').show();
                    $('#export_modal .modal-footer').show();
                }
                //* When there are Errors *//*
                else if (response.code === 1) {
                    $('#export_modal .modal-body .control-group #con_program').html((filter_program == 0)?'All':filter_program_name);
                    $('#export_modal .modal-body .control-group #con_level').html((filter_level == 0)?'All':filter_level);
                    $('#export_modal .modal-body .control-group #con_custom_search').html(search_box);
                    $('#export_modal .modal-body .control-group #con_academic_year').html(filter_academic_session);

                    $('#export_modal .modal-body .control-group strong').html(txt);
                    $('#export_modal .modal-footer #export_cancel_btn').show();
                    $('#export_modal .modal-footer #export_now_btn').hide();
                    $('#export_modal .modal-footer').show();
                }
            },
            error:function (xhr) {
                console.log(xhr.responseText);
            }
        });
    },


    configureExport : function(){
        var self = this;
        $('#export_modal .modal-footer #export_now_btn').click(function(){
            $(this).attr('disabled','disabled').html("Processing Page "+ self.paginate.next_page+". Please Wait ...");
            $('#export_modal .modal-footer #export_cancel_btn').hide();
            self.exportBills();
            //Continue to check if download is done then enable it.
            var url = $("#export-done-url").val();
            var query = ''
            var checker = setInterval(function(){
                $.ajax({
                    url:url,
                    data:query,
                    dataType:'json',
                    type:'POST',
                    success:function (response) {
                        var txt = '';
                        if (typeof response.msg == 'object') {
                            for (megTxt in response.msg) {
                                txt += response.msg[megTxt] + '<br />';
                            }
                        }
                        else {
                            txt = response.msg
                        }
                        if (response.code == 0) {
                            clearInterval(checker);
                            self.initNextExport()
                        }
                    },
                    error:function (xhr) {
                        console.log(xhr.responseText);
                    }
                });
            },1000)//every second
        });
        //;
    },

    initNextExport: function (){
        var self = this;
        var next_page = self.paginate.next_page;
        var page_downloaded = next_page - 1;
        var total_pages = self.paginate.total_pages;
        if(self.paginate.next_page == -1){//We are done exporting

            $('#export_modal .modal-body .control-group strong').html("You have downloaded page "+total_pages+" of "+total_pages +". Export is complete!");
            $('#export_modal .modal-footer #export_now_btn').attr('disabled','disabled').html("Export Finished!");
            $('#export_modal .modal-footer #export_cancel_btn').show();
        }
        else{

            $('#export_modal .modal-body .control-group strong').html("You have downloaded page "+page_downloaded+" of "+total_pages+". Please continue.");
            $('#export_modal .modal-footer #export_now_btn').removeAttr('disabled').html("Next Export Page "+ next_page);
            $('#export_modal .modal-footer #export_cancel_btn').show();
        }
    },

    exportBills: function(){
        var self = this;
        var pag = self.paginate.params;
        $("#print-export-form #data_page").val(self.paginate.next_page);
        $("#print-export-form #data_limit").val(self.export_limit);
        $("#print-export-form #data_query_column").val(pag.search_column);
        $("#print-export-form #data_query").val(pag.search_box);
        $("#print-export-form #data_program").val(pag.filter_program);
        $("#print-export-form #data_level").val(pag.filter_level);
        $("#print-export-form #data_academic_year").val(pag.academic_year);
        window.open('', "PrintExportWindow", "menubar=yes, width=300, height=300,location=no,status=no,scrollbars=yes,resizable=yes");
        $("#print-export-form").submit();

        //Point to next page
        if(self.paginate.next_page == self.paginate.total_pages){//End it
            self.paginate.next_page = -1;
        }
        else{
            self.paginate.next_page = self.paginate.next_page + 1;
        }
    }


};

/* when the page is loaded */
$(document).ready(function () {
    StudentsFee.init();
});